package day03;

/**
 * 一个有效的数独（部分已被填充）不一定是可解的。
 * 只需要根据以上规则，验证已经填入的数字是否有效即可。
 * 空白格用'.'表示。
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：board =
 * [["5","3",".",".","7",".",".",".","."]
 * ,["6",".",".","1","9","5",".",".","."]
 * ,[".","9","8",".",".",".",".","6","."]
 * ,["8",".",".",".","6",".",".",".","3"]
 * ,["4",".",".","8",".","3",".",".","1"]
 * ,["7",".",".",".","2",".",".",".","6"]
 * ,[".","6",".",".",".",".","2","8","."]
 * ,[".",".",".","4","1","9",".",".","5"]
 * ,[".",".",".",".","8",".",".","7","9"]]
 * 输出：true
 * 示例 2：
 * <p>
 * 输入：board =
 * [["8","3",".",".","7",".",".",".","."]
 * ,["6",".",".","1","9","5",".",".","."]
 * ,[".","9","8",".",".",".",".","6","."]
 * ,["8",".",".",".","6",".",".",".","3"]
 * ,["4",".",".","8",".","3",".",".","1"]
 * ,["7",".",".",".","2",".",".",".","6"]
 * ,[".","6",".",".",".",".","2","8","."]
 * ,[".",".",".","4","1","9",".",".","5"]
 * ,[".",".",".",".","8",".",".","7","9"]]
 * 输出：false
 * 解释：除了第一行的第一个数字从 5 改为 8 以外，空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
 */
public class Solution2 {
    public boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
            boolean row[] = new boolean[9];
            boolean col[] = new boolean[9];
            //判断行列
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {   //判断行
                    //判断行上当前数字是否出现过，出现过返回false
                    if (row[board[i][j] - '1'])
                        return false;
                    //将当前数字设置出现标记
                    row[board[i][j] - '1'] = true;
                }
                if (board[j][i] != '.') {   //判断列
                    //判断列上当前数字是否出现过，出现过返回false
                    if (col[board[j][i] - '1'])
                        return false;
                    //将当前数字设置出现标记
                    col[board[j][i] - '1'] = true;
                }
            }
        }
        //判断九宫格
        for (int i = 0; i < 9; i += 3)
            for (int j = 0; j < 9; j += 3) {
                boolean arr[] = new boolean[9];
                for (int k = 0; k < 9; k++) {
                    //k是当前位置，k/3是行下标，k%3是列下标；i,j是基准值
                    char ch = board[k / 3 + i][k % 3 + j];
                    if (ch != '.') {
                        if (arr[ch - '1'])
                            return false;
                        arr[ch - '1'] = true;
                    }
                }
            }
        return true;
    }
}
